package com.canic.dkd.authorization.security;

import com.canic.dkd.authorization.staff.entity.SysRole;
import com.canic.dkd.authorization.staff.entity.SysUser;
import com.canic.dkd.authorization.staff.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByName(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        log.info("用户存在，用户:"+username);
        List<SysRole> roleList = sysUserService.getRoleListByUserId(user.getId());
        List<SimpleGrantedAuthority> userGrantedAuthorities = createAuthorities(roleList);
        //返回数据对象(手动已加密)
        return new User(user.getName(), passwordEncoder.encode(user.getPassword()), userGrantedAuthorities);
    }

    /**
     * @param roleList
     */
    private List<SimpleGrantedAuthority> createAuthorities(List<SysRole> roleList){
        List<SimpleGrantedAuthority> userGrantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
        for (SysRole role : roleList) {
            userGrantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            log.info("role:"+role.toString());
        }
        return userGrantedAuthorities;
    }
}
